package com.easylive.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.easylive.component.RedisComponent;
import com.easylive.dto.TokenUserInfoDto;
import com.easylive.entity.constants.Constants;
import com.easylive.entity.query.UserInfoQuery;
import com.easylive.entity.po.UserInfo;
import com.easylive.entity.vo.ResponseVO;
import com.easylive.exception.BusinessException;
import com.easylive.redis.RedisUtils;
import com.easylive.service.UserInfoService;
import com.easylive.utils.StringTools;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * 用户信息 Controller
 */
@RestController
@RequestMapping("/account")
@Validated
public class AccountController extends ABaseController {

    @Resource
    UserInfoService userInfoService;
    @Resource
    RedisComponent redisComponent;

    @RequestMapping("/checkcode")
    public ResponseVO checkcode() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 42);
        String code = captcha.text();   //验证码结果
        String checkCodeKey = redisComponent.saveCheckCode(code);
        Map<String, Object> result = new HashMap<>();
        result.put("checkCodeKey", checkCodeKey);
        result.put("checkCode", captcha.toBase64());
        return getSuccessResponseVO(result);
    }

    @RequestMapping("/register")
    public ResponseVO register(@NotEmpty @Email @Size(max = 150) String email,
                               @NotEmpty @Size(max = 20) String nickName,
                               @NotEmpty @Pattern(regexp = Constants.REGEX_PASSWORD) String registerPassword,
                               @NotEmpty String checkCodeKey,
                               @NotEmpty String checkCode) {
        try {
            if (!checkCode.equalsIgnoreCase(redisComponent.getCheckCode(checkCodeKey))) {
                throw new BusinessException("图片验证码错误");
            }
            userInfoService.register(email, nickName, registerPassword);
            return getSuccessResponseVO(null);
        } finally {
            redisComponent.delete(checkCodeKey);
        }
    }


    @RequestMapping("/login")
    public ResponseVO login(HttpServletResponse response,
                            @NotEmpty @Email @Size(max = 150) String email,
                            @NotEmpty String password,
                            @NotEmpty String checkCodeKey,
                            @NotEmpty String checkCode) {
        try {
            if (!checkCode.equalsIgnoreCase(redisComponent.getCheckCode(checkCodeKey))) {
                throw new BusinessException("图片验证码错误");
            }
            String ip = getIpAddr();
            TokenUserInfoDto tokenUserInfoDto = userInfoService.login(email, password, ip);
            saveToken2Cookie(response, tokenUserInfoDto.getToken());   //保存token用户信息到cookie
            //TODO 设置粉丝数 关注数 硬币数
            deleteCookie();
            return getSuccessResponseVO(tokenUserInfoDto);
        } finally {
            redisComponent.delete(checkCodeKey);
        }
    }

    /**
     * 删除该用户在redis中还没过期的token用户信息
     */
    private void deleteCookie() {
        //清除token
        HttpServletRequest request = getRequest();
        Cookie[] cookies = request.getCookies();
        if(null != cookies) {
            String token = null;
            for (Cookie cookie : cookies) {
                if (Constants.TOKEN_ADMIN.equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
            if (!StringTools.isEmpty(token)) {
                redisComponent.cleanToken4Admin(token);
            }
        }
    }

    @RequestMapping("/autoLogin")
    public ResponseVO autoLogin(HttpServletResponse response) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        if (tokenUserInfoDto == null) {
            return getSuccessResponseVO(null);
        }
        if (tokenUserInfoDto.getExpireAt() - System.currentTimeMillis() < Constants.TIME_SECOND_ONE_DAY) {
            // token过期时间小于一天，则刷新token
            redisComponent.saveTokenInfo(tokenUserInfoDto);
        }
        saveToken2Cookie(response, tokenUserInfoDto.getToken());
        //TODO 设置粉丝数 关注数 硬币数
        return getSuccessResponseVO(tokenUserInfoDto);
    }

    @RequestMapping("/loginOut")
    public ResponseVO loginOut(HttpServletResponse response, HttpServletRequest request) {
        cleanCookie(response);
        return getSuccessResponseVO(null);
    }


}